import 'dart:async';
import 'dart:convert';

import 'package:common_utils/common_utils.dart';
import 'package:extended_image/extended_image.dart';
import 'package:flutter/foundation.dart';
import 'package:yp/config/config.dart';
import 'package:yp/utils/util.dart';
import 'package:get/get.dart';
import 'package:yp/services/api.dart';
import 'package:intl/intl.dart';
import 'package:sp_util/sp_util.dart';
import '../../../../helper.dart';
import 'state.dart';
import 'package:logger/logger.dart';
import 'package:fluwx/fluwx.dart' as fluwx;

import 'package:yp/pages/address_selector/address_model.dart';

class FontSaleOrderLogic extends GetxController {
  final state = FontSaleOrderState();
  final type = Get.arguments == null ? 1 : Get.arguments['type'];
  final arguments = Get.arguments;
  var logger = Logger(
    printer: PrettyPrinter(),
  );
  var activeId;

  @override
  void onInit() {
    super.onInit();
    print(arguments);

    fluwx.weChatResponseEventHandler.listen((event) {
      if (event is fluwx.WeChatLaunchMiniProgramResponse) {
        /// 取消支付：extMsg:{"errMsg":"requestPayment:fail cancel","status":"30"}
        /// 支付成功 extMsg:{"errMsg":"requestPayment:ok","status":"20"}
        Map resultMap = json.decode(event.extMsg);
        if (resultMap != null) {
          if (resultMap["status"].toString() == "20") {
            print("支付结果1");
            print(SpUtil.getString('dingdan'));
            setMoneyOver(
                SpUtil.getString('dingdan'), 1, 'pintuan', 'success', 'a');
          } else {
            toast("支付失败");
          }
        } else {
          print("支付结果3");
          setMoneyOver(SpUtil.getString('dingdan'), 0, 'pintuan', 'err', 'a');
        }
      }
    });
  }

  @override
  void onReady() {
    super.onReady();
    activeId = arguments['ecactivity_id'];
    // selfHelpAddress();
    getGiftCard();
    getCurrentLocationInfo(success: (data) {
      state.orderAddress = data['addressInfo'];

      var params = {
        // "data_sign": 0,
        "channel_num_id": 99,
        "use_platform": 2,
        "usr_num_id": SpUtil.getInt('empeNumId'),
        "ec_shop_num_id": arguments['shop_id'],
        "tran_type_num_id": 3,
        "ecactivity_id": arguments['ecactivity_id'],
        "norm_qty": 1,
        "item_num_id": arguments['item_num_id'],
        "so_sign": 20
      };

      Api.fontMoneySaleOrderDetail(params).listen((event) {
        print(event);
        state.depositAmount = event['deposit_amount'];
        state.balanceAmount = event['balance_amount'];
        state.dueTime = event['due_time'];
        if (event['integral'] == null) {
          state.showJiFen = false;
        }
        state.goodsItem = event["settle_shop_item_list"];
        List list = event["settle_shop_item_list"];
        list?.forEach((element) {
          element['ec_packages'].forEach((item) {
            item['cartitemlist'].forEach((itm) {
              int num = itm['quantity'].toInt();
              state.number = num++;
              print(num);
            });
          });
        });

        state.isCoupons = event["able_discount_coupons"];
        if (event["able_discount_coupons"] != null) {
          List arr = event["able_discount_coupons"];

          arr.forEach((element) {
            if (element['show_status'] == 1) {
              state.couponName = element['qname'];
              state.couponData = element;
            }
          });
        }
        if (event["able_cash_coupons"] != null) {
          List arr1 = event["able_cash_coupons"];
          arr1.forEach((element) {
            if (element['show_status'] == 1) {
              state.couponName = element['qname'];
              state.couponData = element;
            }
          });
        }
        if (event["able_freight_coupons"] != null) {
          List arr2 = event["able_freight_coupons"];
          arr2.forEach((element) {
            if (element['show_status'] == 1) {
              state.couponName = element['qname'];
              state.couponData = element;
            }
          });
        }
        setcouponArr(event);
        update();
      });
      update();
    });
  }

  ///获取礼品卡
  void getGiftCard() {
    var params = {
      "use_platform": 2,
      "usr_num_id": SpUtil.getInt('empeNumId'),
      'access_token': SpUtil.getString('token'),
      "card_status": 3, //购物卡状态 (1: 有效, 2:失效, 3: 可用)
    };
    Api.walletInformation(params).listen((event) {
      state.GiftcardList = event['available_cards'];
      state.GiftcardList.forEach((element) {
        element['click'] = false;
      });
    });
  }

  clickGift(index) {
    setcard(state, index);
    // state.isGiftMoney=10;
    update();
  }

  bool panduan() {
    if (state.orderAddress == null || state.orderAddress['prv_name'] == null) {
      toast("请选择地址");
      return false;
    }
    return true;
  }

  void selectCoupon(index, item) {
    // var clostate =  state.couponList[index]['show_status'];
    // state.couponList.forEach((element) {
    //
    //  });
    bool iss = panduan();
    if (iss) {
      state.couponData = item;
      if (state.couponList[index]['show_status'] == 1) {
        state.couponList[index]['show_status'] = 3;
        state.couponData['show_status'] = 3;
      } else {
        state.couponList[index]['show_status'] = 1;
        state.couponData['show_status'] = 1;
      }
      if (state.couponData['show_status'] == 3) {
        state.couponName = '';
      }
      if (state.couponList[index]['show_status'] == 1) {
        state.couponName = item['qname'];
        state.couponId = item['activityid'];
        state.qmz = item['qmz'];
      }
      update();
      submitCoupon();
    }
  }

  void submitCoupon() {
    getCurrentLocationInfo(success: (data) {
      state.orderAddress = data['addressInfo'];
      var item = state.couponData;
      var params = {
        "data_sign": 0,
        'g_buy_norm_num_id': arguments['g_buy_norm_num_id'],
        "norm_qty": arguments['shopnum'],
        "so_sign": 0,
        'g_buy_apply_id': arguments['g_buy_apply_id'],
        "is_first": 1,
        // "supply_unit_num_id": arguments['supply_unit_num_id'],
        "usr_num_id": SpUtil.getInt('empeNumId'),
        "use_platform": 2,
        'access_token': SpUtil.getString('token'),
        "tran_type_num_id": 3,
        "prv_num_id": state.isZiTi ? state.a : state.orderAddress['prv_num_id'],
        "city_num_id":
            state.isZiTi ? state.b : state.orderAddress['city_num_id'],
        "city_area_num_id":
            state.isZiTi ? state.c : state.orderAddress['city_area_num_id'],
        "town_num_id":
            state.isZiTi ? state.d : state.orderAddress['town_num_id'],
        "maplocation_x": state.isZiTi
            ? state.maplocationX
            : state.orderAddress['maplocation_x'],
        "maplocation_y": state.isZiTi
            ? state.maplocationY
            : state.orderAddress['maplocation_y'],
        "adr_num_id": state.isZiTi
            ? state.sub_unit_num_id
            : state.orderAddress["adr_num_id"],
        'is_switch': 1,

        "ec_shop_num_id": arguments['shop_id'], //商品详情的店铺
        "item_num_id": arguments['item_num_id'], //商品详情的商品shop_id
        "quantity": arguments['shopnum'],
        "style_num_id": arguments['style_num_id'], //商品详情的店铺
        "ec_style_num_id": arguments['ec_style_num_id'], //商品详情的店铺
        //使用积分传数值
        "integral": null,
        "adr_type": state.isZiTi ? 1 : 0,
        "is_logistics_cart": '1',
      };
      print('state.orderAddress["adr_num_id"]');
      print(state.isZiTi);
      print(state.orderAddress["adr_num_id"]);
      if (item['show_status'] == 3) {
        params['select_discount_coupons'] = [];
        params['select_cash_coupons'] = [];
        params['select_freight_coupons'] = [];
      } else {
        if (item['type'] == 1) {
          params['select_discount_coupons'] = [
            {'ticket_id': item['activityid'], 'coupon_no': item['qbarcode']}
          ];
        } else if (item['type'] == 2) {
          params['select_cash_coupons'] = [
            {'ticket_id': item['activityid'], 'coupon_no': item['qbarcode']}
          ];
        } else {
          params['select_freight_coupons'] = [
            {'ticket_id': item['activityid'], 'coupon_no': item['qbarcode']}
          ];
        }
      }

      Api.grouporder(params).listen((event) {
        // 默认地址信息
        var params1 = {
          'usr_num_id': SpUtil.getInt('empeNumId'),
          'access_token': SpUtil.getString('token'),
        };

        state.goodsItem = event["settle_shop_item_list"];
        List list = event["settle_shop_item_list"];
        list.forEach((element) {
          element['ec_packages'].forEach((item) {
            item['cartitemlist'].forEach((itm) {
              int num = itm['quantity'].toInt();
              state.number = num++;
              print(num);
            });
          });
        });
        state.isCoupons = event["able_discount_coupons"];
        setcouponArr(event);
        update();
      });
    });
  }

  // ///调用接口前，保持优惠卷状态
  //  getclickCoupon(){
  //       // state.couponList;
  //           List arr=[[],[],[]];
  //           for(var i=0;i<state.couponList.length;i++){
  //               if(state.couponList[i]['type'] == 1){
  //                 arr[0].add(state.couponList[i]);
  //               }
  //               if(state.couponList[i]['type'] == 2){
  //                 arr[1].add(state.couponList[i]);
  //               }
  //                if(state.couponList[i]['type'] == 3){
  //                 arr[2].add(state.couponList[i]);
  //               }
  //           }
  //           return arr;
  //  }
  ///设置优惠卷
  void setcouponArr(event) {
    print('-----------$event--------------');
    List newarr = [];
    List nonewarr = [];
    if (event["able_discount_coupons"] != null) {
      List arr = event["able_discount_coupons"];
      arr.forEach((element) {
        element['type'] = 1;
      });
      arr.forEach((element) {
        newarr.add(element);
      });
    }
    if (event["able_cash_coupons"] != null) {
      List arr1 = event["able_cash_coupons"];
      arr1.forEach((element) {
        element['type'] = 2;
      });
      arr1.forEach((element) {
        newarr.add(element);
      });
    }
    if (event["able_freight_coupons"] != null) {
      List arr2 = event["able_freight_coupons"];
      arr2.forEach((element) {
        element['type'] = 3;
      });
      arr2.forEach((element) {
        newarr.add(element);
      });
    }

    if (event["disable_discount_coupons"] != null) {
      List arr3 = event["disable_discount_coupons"];

      arr3.forEach((element) {
        nonewarr.add(element);
      });
    }
    if (event["disable_cash_coupons"] != null) {
      List arr4 = event["disable_cash_coupons"];

      arr4.forEach((element) {
        nonewarr.add(element);
      });
    }
    if (event["disable_freight_coupons"] != null) {
      List arr5 = event["disable_freight_coupons"];

      arr5.forEach((element) {
        nonewarr.add(element);
      });
    }
    state.couponList = newarr;
    state.nocouponList = nonewarr;

    state.total = event["total"];
    state.iscou = true;
  }

  void selectSwitch() {
    state.isJiFen = !state.isJiFen;
    // print('orderAddressorderAddressorderAddressorderAddressorderAddressorderAddress');
    //   print( state.orderAddress);
    if (state.orderAddress == null) {
      toast('请选择地址');
    }

    var params = {
      "data_sign": 0,
      'g_buy_norm_num_id': arguments['g_buy_norm_num_id'],
      "norm_qty": arguments['shopnum'],
      "so_sign": 0,
      'g_buy_apply_id': arguments['g_buy_apply_id'],
      "is_first": 1,
      "supply_unit_num_id": arguments['supply_unit_num_id'],
      "usr_num_id": SpUtil.getInt('empeNumId'),
      // "emp_num_id": SpUtil.getInt('empeNumId'),
      "use_platform": 2,
      'is_switch': 1,

      "ec_shop_num_id": arguments['shop_id'], //商品详情的店铺
      "item_num_id": arguments['item_num_id'], //商品详情的商品shop_id
      "quantity": arguments['shopnum'],
      "style_num_id": arguments['style_num_id'], //商品详情的店铺
      "ec_style_num_id": arguments['ec_style_num_id'], //商品详情的店铺
      "tran_type_num_id": 3,
      "prv_num_id": state.isZiTi ? state.a : state.orderAddress['prv_num_id'],
      "city_num_id": state.isZiTi ? state.b : state.orderAddress['city_num_id'],
      "city_area_num_id":
          state.isZiTi ? state.c : state.orderAddress['city_area_num_id'],
      "town_num_id": state.isZiTi ? state.d : state.orderAddress['town_num_id'],
      "maplocation_x": state.isZiTi
          ? state.maplocationX
          : state.orderAddress['maplocation_x'],
      "maplocation_y": state.isZiTi
          ? state.maplocationY
          : state.orderAddress['maplocation_y'],
      "adr_num_id": state.isZiTi
          ? state.sub_unit_num_id
          : state.orderAddress["adr_num_id"],
      //使用积分传数值
      "integral": null,
      "adr_type": state.isZiTi ? 1 : 0,
      'access_token': SpUtil.getString('token'),
      "is_logistics_cart": '1',
    };
    var item = state.couponData;

    if (item != null) {
      if (item['show_status'] == 3) {
        params['select_discount_coupons'] = [];
        params['select_cash_coupons'] = [];
        params['select_freight_coupons'] = [];
      } else {
        if (item['type'] == 1) {
          params['select_discount_coupons'] = [
            {'ticket_id': item['activityid'], 'coupon_no': item['qbarcode']}
          ];
        } else if (item['type'] == 2) {
          params['select_cash_coupons'] = [
            {'ticket_id': item['activityid'], 'coupon_no': item['qbarcode']}
          ];
        } else {
          params['select_freight_coupons'] = [
            {'ticket_id': item['activityid'], 'coupon_no': item['qbarcode']}
          ];
        }
      }
    } else {
      params['is_switch'] = 0;
    }

    Api.grouporder(params).listen((event) {
      print(">>>>>>>>>>>>>>>$event");
      // state.dianAdr = '${event['prv_name']}${event['city_name']}${event['city_area_name']}${event['adr']}' ;
      // if (state.orderAddress != null) {
      //   state.orderAddress = event["member_adr"];
      // }

      state.goodsItem = event["settle_shop_item_list"];
      List list = event["settle_shop_item_list"];
      list.forEach((element) {
        element['ec_packages'].forEach((item) {
          item['cartitemlist'].forEach((itm) {
            int num = itm['quantity'].toInt();
            state.number = num++;
            print(num);
          });
        });
      });
      state.isCoupons = event["able_discount_coupons"];
      List newarr = [];
      setcouponArr(event);

      update();
    });
  }

  void selectSwitch1() {
    getCurrentLocationInfo(success: (data) {
      state.orderAddress = data['addressInfo'];
      var params = {
        "data_sign": 0,
        'g_buy_norm_num_id': arguments['g_buy_norm_num_id'],
        "norm_qty": arguments['shopnum'],
        "so_sign": 0,
        'g_buy_apply_id': arguments['g_buy_apply_id'],
        "is_first": 1,
        "supply_unit_num_id": arguments['supply_unit_num_id'],
        "usr_num_id": SpUtil.getInt('empeNumId'),
        'access_token': SpUtil.getString('token'),
        "use_platform": 2,
        "tran_type_num_id": 3,
        "prv_num_id": state.orderAddress['prv_num_id'],
        "city_num_id": state.orderAddress['city_num_id'],
        "city_area_num_id": state.orderAddress['city_area_num_id'],
        "town_num_id": state.orderAddress['town_num_id'],
        "maplocation_x": state.orderAddress['maplocation_x'],
        "maplocation_y": state.orderAddress['maplocation_y'],
        "adr_num_id": state.orderAddress["adr_num_id"],
        "ec_shop_num_id": arguments['shop_id'], //商品详情的店铺
        "item_num_id": arguments['item_num_id'], //商品详情的商品shop_id
        "quantity": arguments['shopnum'],
        "style_num_id": arguments['style_num_id'], //商品详情的店铺
        "ec_style_num_id": arguments['ec_style_num_id'], //商品详情的店铺
        //使用积分传数值
        "integral": null,
        "adr_type": 0,
        "is_logistics_cart": '1',
      };
      var item = state.couponData;
      print('输出输出输出输出输出输出输出输出输出输出输出输出');
      print(state.orderAddress);
      if (item != null) {
        if (item['show_status'] == 3) {
          params['select_discount_coupons'] = [];
          params['select_cash_coupons'] = [];
          params['select_freight_coupons'] = [];
        } else {
          if (item['type'] == 1) {
            params['select_discount_coupons'] = [
              {'ticket_id': item['activityid'], 'coupon_no': item['qbarcode']}
            ];
          } else if (item['type'] == 2) {
            params['select_cash_coupons'] = [
              {'ticket_id': item['activityid'], 'coupon_no': item['qbarcode']}
            ];
          } else {
            params['select_freight_coupons'] = [
              {'ticket_id': item['activityid'], 'coupon_no': item['qbarcode']}
            ];
          }
        }
      } else {
        params['is_switch'] = 0;
      }
      Api.grouporder(params).listen((event) {
        if (state.orderAddress != null) {
          state.orderAddress = event["member_adr"];
        }

        state.goodsItem = event["settle_shop_item_list"];
        List list = event["settle_shop_item_list"];
        list.forEach((element) {
          element['ec_packages'].forEach((item) {
            item['cartitemlist'].forEach((itm) {
              int num = itm['quantity'].toInt();
              state.number = num++;
              print(num);
            });
          });
        });
        state.isCoupons = event["able_discount_coupons"];
        setcouponArr(event);
        update();
      });
    });
  }

  void selectDian(int i, item) {
    print('>>>>>>>>>$item');
    state.selected = i;
    state.a = item['prv_num_id'];
    state.b = item['city_num_id'];
    state.c = item['city_area_num_id'];
    state.d = item['town_num_id'];
    state.maplocationX = item['maplocation_x'];
    state.maplocationY = item['maplocation_y'];
    state.sub_unit_num_id = item['sub_unit_num_id'];
    state.dianAdr = item['prv_name'] +
        item['city_name'] +
        item['city_area_name'] +
        item['adr'];
    var params = {
      "data_sign": 0,
      'g_buy_norm_num_id': arguments['g_buy_norm_num_id'],
      "norm_qty": arguments['shopnum'],
      "so_sign": 0,
      'g_buy_apply_id': arguments['g_buy_apply_id'],
      "is_first": 1,
      "supply_unit_num_id": arguments['supply_unit_num_id'],
      "usr_num_id": SpUtil.getInt('empeNumId'),
      // "emp_num_id": SpUtil.getInt('empeNumId'),
      "use_platform": 2,
      "ec_shop_num_id": arguments['shop_id'], //商品详情的店铺
      "item_num_id": arguments['item_num_id'], //商品详情的商品shop_id
      "quantity": arguments['shopnum'],
      "style_num_id": arguments['style_num_id'], //商品详情的店铺
      "ec_style_num_id": arguments['ec_style_num_id'], //商品详情的店铺
      "tran_type_num_id": 3,
      "prv_num_id": state.a,
      "city_num_id": state.b,
      "city_area_num_id": state.c,
      "town_num_id": state.d,
      "maplocation_x": state.maplocationX,
      "maplocation_y": state.maplocationY,
      "adr_num_id": state.sub_unit_num_id,
      "adr_type": 1,
      'is_switch': 1,
      'access_token': SpUtil.getString('token'),
      "is_logistics_cart": '1',
    };
    var items = state.couponData;
    if (items != null) {
      if (items['show_status'] == 3) {
        params['select_discount_coupons'] = [];
        params['select_cash_coupons'] = [];
        params['select_freight_coupons'] = [];
      } else {
        if (items['type'] == 1) {
          params['select_discount_coupons'] = [
            {'ticket_id': items['activityid'], 'coupon_no': items['qbarcode']}
          ];
        } else if (items['type'] == 2) {
          params['select_cash_coupons'] = [
            {'ticket_id': items['activityid'], 'coupon_no': items['qbarcode']}
          ];
        } else {
          params['select_freight_coupons'] = [
            {'ticket_id': items['activityid'], 'coupon_no': items['qbarcode']}
          ];
        }
      }
    } else {
      params['is_switch'] = 0;
    }
    Api.grouporder(params).listen((event) {
      // state.orderAddress = event["member_adr"];
      state.goodsItem = event["settle_shop_item_list"];
      List list = event["settle_shop_item_list"];

      list.forEach((element) {
        element['ec_packages'].forEach((item) {
          item['cartitemlist'].forEach((itm) {
            int num = itm['quantity'].toInt();
            state.number = num++;
            print(num);
          });
        });
      });
      setcouponArr(event);
      update();
    });
    update();
  }

  void submitDian() {
    if (!state.iszitibutton) {
      return;
    }
    state.isZiTi = true;
    state.adr = state.dianAdr;
    int index = state.selected;
    var item = state.selfHelpAddressList[index];
    state.a = item['prv_num_id'];
    state.b = item['city_num_id'];
    state.c = item['city_area_num_id'];
    state.d = item['town_num_id'];
    state.maplocationX = item['maplocation_x'];
    state.maplocationY = item['maplocation_y'];
    state.sub_unit_num_id = item['sub_unit_num_id'];
    state.dianAdr = item['prv_name'] +
        item['city_name'] +
        item['city_area_name'] +
        item['adr'];
    var params = {
      "is_first": 1,
      "supply_unit_num_id": arguments['supply_unit_num_id'],
      "usr_num_id": SpUtil.getInt('empeNumId'),
      // "emp_num_id": SpUtil.getInt('empeNumId'),
      "use_platform": 2,
      "tran_type_num_id": 3,
      "prv_num_id": state.a,
      "city_num_id": state.b,
      "city_area_num_id": state.c,
      "town_num_id": state.d,
      "maplocation_x": state.maplocationX,
      "maplocation_y": state.maplocationY,
      "adr_num_id": state.sub_unit_num_id,
      "adr_type": 1,
      'is_switch': 1,
      "integral": null,
      'access_token': SpUtil.getString('token'),
      "data_sign": 0,
      "norm_qty": arguments['shopnum'],
      "so_sign": 0,
      'g_buy_apply_id': arguments['g_buy_apply_id'],
      "quantity": arguments['shopnum'],
      'g_buy_norm_num_id': arguments['g_buy_norm_num_id'],
      "ec_shop_num_id": arguments['shop_id'], //商品详情的店铺
      "item_num_id": arguments['item_num_id'], //商品详情的商品shop_id
      "style_num_id": arguments['style_num_id'], //商品详情的店铺
      "ec_style_num_id": arguments['ec_style_num_id'], //商品详情的店铺
      "is_logistics_cart": '1',
    };
    var items = state.couponData;
    // print('state.couponData state.couponData state.couponData state.couponData');
    // print(items);
    // return;
    if (items != null) {
      if (item['show_status'] == 3) {
        params['select_discount_coupons'] = [];
        params['select_cash_coupons'] = [];
        params['select_freight_coupons'] = [];
      } else if (item['show_status'] == 1) {
        if (items['type'] == 1) {
          params['select_discount_coupons'] = [
            {'ticket_id': items['activityid'], 'coupon_no': items['qbarcode']}
          ];
        } else if (item['type'] == 2) {
          params['select_cash_coupons'] = [
            {'ticket_id': items['activityid'], 'coupon_no': items['qbarcode']}
          ];
        } else {
          params['select_freight_coupons'] = [
            {'ticket_id': items['activityid'], 'coupon_no': items['qbarcode']}
          ];
        }
      } else {
        params['select_discount_coupons'] = [];
        params['select_cash_coupons'] = [];
        params['select_freight_coupons'] = [];
      }
    } else {
      params['is_switch'] = 0;
    }
    print('入参数');
    print(params);
    Api.grouporder(params).listen((event) {
      state.isZiTi = true;
      // state.orderAddress = event["member_adr"];
      state.goodsItem = event["settle_shop_item_list"];
      List list = event["settle_shop_item_list"];
      list.forEach((element) {
        element['ec_packages'].forEach((item) {
          item['cartitemlist'].forEach((itm) {
            int num = itm['quantity'].toInt();
            state.number = num++;
            print(num);
          });
        });
      });
      state.isCoupons = event["able_discount_coupons"];
      state.isCoupons = event["able_discount_coupons"];
      setcouponArr(event);
      update();
    });
    update();
  }

  void selfHelpAddress() {
    state.selfHelpAddressList = [];
    var params = {
      'is_pick_up': 1,

      "prv_num_id": state.orderAddress['prv_num_id'],
      "city_num_id": state.orderAddress['city_num_id'],
      "city_area_num_id": state.orderAddress['city_area_num_id'],
      "town_num_id": state.orderAddress['town_num_id'],
      "maplocation_x": state.orderAddress['maplocation_x'],
      "maplocation_y": state.orderAddress['maplocation_y'],
      "adr_num_id": state.orderAddress["adr_num_id"],

      "page": 1,
      "page_size": 10,
      // 'usr_num_id': SpUtil.getInt('empeNumId')
    };
    print('自提点自提点自提点自提点自提点自提点');
    print(params);
    Api.selfHelpAddress(params).listen((event) {
      if (event['sub_unit_shop_list'].length > 0) {
        state.iszitibutton = true;
        state.selfHelpAddressList = event['sub_unit_shop_list'];
        var item = event['sub_unit_shop_list'][0];
        state.dianAdr = item['prv_name'] +
            item['city_name'] +
            item['city_area_name'] +
            item['adr'];
      } else {
        state.iszitibutton = false;
      }
      update();
    });
  }

  //结算页优惠券选择
  void orderCouponSelect() {
    var params = {
      "usr_num_id": SpUtil.getString('userNumId'),
      "emp_num_id": SpUtil.getInt('empeNumId'),
      "use_platform": 2,
      "tran_type_num_id": 3,
      "adr_type": 0,
    };
    Api.orderCouponSelect(params).listen((event) {
      update();
    });
  }

  /// 选择支付方式
  void setPayType(int index) {
    state.paytype = index;
    update();
  }

  /// 选择尾款预计付款时间
  void selectDate(DateTime value) {
    state.time = value;
    state.time1 = '${DateFormat("yyyy-MM-dd").format(value)}';
    update();
  }

  /// 输入订金计算尾款
  void countMoney(value) {
    if (!isNumber(value)) {
      state.controller1.clear();
      state.endMoney = null;
      state.startMoney = null;
      return;
    } else if (double.parse(value.toString().isEmpty ? '0' : value) < 0) {
      toast('定金金额不能小于0');
      state.controller1.clear();
      state.startMoney = null;
      state.endMoney = null;
      update();
    } else if (double.parse(value.toString().isEmpty ? '0' : value) >
        state.total["all_payment"]) {
      toast('定金金额不能大于商品金额');
      state.controller1.clear();
      state.startMoney = null;
      state.endMoney = null;
      update();
    } else {
      var dj = double.parse(value.toString().isEmpty ? '0' : value);
      var money = state.total["all_payment"] - dj;
      state.endMoney =
          (NumUtil.getNumByValueDouble(money, 2)).toStringAsFixed(2); // 保留两位小数
      state.startMoney =
          (NumUtil.getNumByValueDouble(dj, 2)).toStringAsFixed(2); // 保留两位小数
    }
    update();
  }

  bool isNumber(String value) {
    if (value == null) {
      return true;
    }
    final n = num.tryParse(value);
    return n != null;
  }

  //提交订单数据
  void orderSubmit() {
    if (state.orderAddress == null) {
      toast("请选择地址");
      return;
    }

    var params = {
      // "data_sign": 0,
      "channel_num_id": 99,
      "use_platform": 2,
      "so_sign": 20,
      "ecactivity_id": arguments['ecactivity_id'],
      "item_num_id": arguments['item_num_id'],
      "ec_shop_num_id": arguments['shop_id'],
      "usr_num_id": SpUtil.getInt('empeNumId'),
      "tran_type_num_id": 3,
      "norm_qty": arguments['shopnum'],
      "adr_num_id": state.orderAddress["adr_num_id"],
      "tml_type": 0,
      "remark": state.remarkList[state.remarkType]['remark'],
      "buyer_memo": "",
      "consumer_telephone": '',
    };
    // print('print');
    // print(arguments);
    // print(params);

    var item = state.couponData;
    if (item != null) {
      if (item['show_status'] == 3) {
        params['select_discount_coupons'] = [];
        params['select_cash_coupons'] = [];
        params['select_freight_coupons'] = [];
      } else {
        if (item['type'] == 1) {
          params['select_discount_coupons'] = [
            {'ticket_id': item['activityid'], 'coupon_no': item['qbarcode']}
          ];
        } else if (item['type'] == 2) {
          params['select_cash_coupons'] = [
            {'ticket_id': item['activityid'], 'coupon_no': item['qbarcode']}
          ];
        } else {
          params['select_freight_coupons'] = [
            {'ticket_id': item['activityid'], 'coupon_no': item['qbarcode']}
          ];
        }
      }
    }

    Api.fontMoneySaleOrderSubmit(params).listen((event) {
      print(event);
      if (event["code"] == 0) {
        // state.total["all_payment"] = event['need_pay_amount'];
        state.total["all_payment"] = event['trade_amount'];
        var params1;
        if (kIsWeb == true) {
          params1 = {
            "out_trade_no": event["tml_num_id"].toString(),
            "plat_type": 7,
            // "body": "jifen",
            "body": "提交预支付",
            "pay_way": 0,
            "use_platform": 1,
            'access_token': SpUtil.getString('token'),
            // 'appid': Config.ZJ_APPID,
          };
        } else {
          params1 = {
            "out_trade_no": event["tml_num_id"].toString(),
            "plat_type": 7,
            "body": "jifen",
            "pay_way": 0,
            "use_platform": Config.use_plat_form,
            'access_token': SpUtil.getString('token'),
            'appid': Config.ZJ_APPID,
          };
        }
        SpUtil.putString('pay_type', 'list');
        // SpUtil.putDouble('need_pay_amount', event['trade_amount']);
        SpUtil.putString('tml_num_id', event['tml_num_id']);
        // return;
        if (state.GiftcardList.length > 0) {
          gotomoney(state, startCPCNWeixinPay, params1,
              event["tml_num_id"].toString());
        } else {
          //获取openid
          // getopenid();
          Api.orderPayment(params1).listen((event2) {
            SpUtil.putString('dingdan', event['tml_num_id']);
            state.shifu = event2['pay_response']['coupon_fee'];
            print('我要去支付了');
            // print(jsonDecode(event2['pre_pay_no']));
            // var payjson = jsonDecode(event2['pre_pay_no']);
            print('kIsWeb ==true');
            print(kIsWeb == true);
            if (kIsWeb == true) {
              webpay(event2['pre_pay_no']);
            } else {
              startCPCNWeixinPay(event2['pre_pay_no']);
            }
          });
        }
      } else {
        toast(event["message"]);
      }
    });
  }

  /// 拉起中金支付
  void startCPCNWeixinPay(String authCode) async {
    if (authCode.isEmpty) {
      toast("签名失败");
      return;
    }
    var result =
        fluwx.payWithCPCN(appId: Config.WECHAT_APPID, authCode: authCode);
    print("=========结果<<<$result>>>====");
  }
}
